package com.alogic.validator.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import com.alogic.validator.Validator;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * 正则表达式匹配
 * @author yyduan
 * @since 1.6.12.11 [20181206 duanyy] <br>
 *
 * @version 1.6.13.17 [20200923 duanyy] <br>
 * - 优化validator接口
 *
 * @version 1.6.13.25 [20201110 duanyy] <br>
 * - 修复validator的问题
 */
public class Regx extends Validator.Abstract{
	protected Pattern pattern = null;
	protected boolean exclude = false;
	@Override
	public void configure(Properties p) {
		super.configure(p);
		exclude = PropertiesConstants.getBoolean(p,"exclude",exclude,true);
		String regex = PropertiesConstants.getString(p,"pattern","",true);
		if (StringUtils.isNotEmpty(regex)){
			try {
				pattern = Pattern.compile(regex);
			}catch (Exception ex){
				LOG.error(ExceptionUtils.getStackTrace(ex));
			}
		}		
	}	
	
	@Override
	public boolean check(String value, Properties ctx,boolean throwException) {
		boolean result = true;
		if (pattern != null){
			Matcher matcher = pattern.matcher(value);
			result = exclude?!matcher.matches():matcher.matches();
		}
		if (!result && throwException){
			throw new BaseException(getCode(ctx),getMessage(ctx));
		}
		return result;
	}

	@Override
	public boolean check(String value, Properties ctx, Listener listener) {
		boolean result = true;
		if (pattern != null){
			Matcher matcher = pattern.matcher(value);
			result = exclude?!matcher.matches():matcher.matches();
		}

		if (listener != null){
			listener.result(result,value,this,ctx);
		}
		return result;
	}
}
